<template>
  <div>
    <a-button
      v-if="logined"
      @click="showModal('新增',1)"
      type="primary">
      <template #icon><PlusOutlined /></template>
      新增
    </a-button>
    <a-table
      :rowKey="record=>record.serialNumber"
      :loading="loading"
      :columns="projectColumns"
      :data-source="dataSource"
      :scroll="{y:650}"
      :pagination="pagination"
      :customRow="logined ? customRow : () => {}"
      size="small"
      style="margin-top:10px">
      <template #childrenNumber="{ record }">
        <span v-if="record.childrenNumber*1 === 0">{{record.childrenNumber}}</span>
        <a-button
          v-else
          @click="handleSoftTo(record.id)"
          type="link"
          size="small">
          {{record.childrenNumber}}
        </a-button>
      </template>
      <template #imgUrl="{ record }">
        <div class="imgUrl" @click="handlePreview(record.imgUrl)">
          <a-avatar shape="square" :src="record.imgUrl" />
        </div>
      </template>
      <template #action="{ record }">
        <span>
          <a-button v-if="logined" type="primary" size="small" style="margin-right:10px" @click="showModal('修改',3,record)">
            修改
          </a-button>
          <a-popconfirm
            :title="`确定删除${record.name}项目?`"
            ok-text="确定"
            cancel-text="取消"
            @confirm="confirmDelete(record)">
            <a-button type="danger" size="small" v-if="logined">
              删除
            </a-button>
          </a-popconfirm>
        </span>
      </template>
    </a-table>
    <a-modal
      :title="modalConfig.title"
      v-model:visible="modalConfig.visible"
      :confirm-loading="loading"
      :destroyOnClose="true"
      @ok="handleOk">
      <SoftProjectSetting
        ref="RefProjectSetting"
        :loading="loading"
        :type="modalConfig.type"
        :projectRow="modalConfig.projectRow"
        @handle-project="handleProject"/>
    </a-modal>
    <a-modal
      :visible="imgModal.visible"
      :footer="null"
      @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="imgModal.src" />
    </a-modal>
  </div>
</template>

<script>
import { ref, onMounted, reactive, getCurrentInstance, computed } from 'vue'
import { useStore } from 'vuex'
import { projectColumns } from '../soft.config'
import SoftProjectSetting from './SoftProjectSetting'
import {
  PlusOutlined
} from '@ant-design/icons-vue'
export default {
  components: {
    PlusOutlined,
    SoftProjectSetting
  },
  setup (props, context) {
    const { proxy } = getCurrentInstance()
    const store = useStore()
    // eslint-disable-next-line prefer-const
    let loading = ref(false)
    // eslint-disable-next-line prefer-const
    let dataSource = ref([])
    const modalConfig = reactive({
      title: '',
      visible: false,
      type: 1,
      projectRow: {}
    })
    const imgModal = reactive({
      visible: false,
      src: ''
    })
    const pagination = reactive({
      size: '20',
      showSizeChanger: true
    })
    const dragStartRow = ref({})
    const dropRow = ref({})
    onMounted(() => {
      loading.value = true
      searchProjetList()
    })
    const searchProjetList = async () => {
      const { errCode, data } = await proxy.$root.$axios.getProjetList()
      if (errCode * 1 === 0) {
        dataSource.value = data.map((item, index) => {
          return {
            ...item,
            serialNumber: index + 1
          }
        })
        store.state.project = data
        store.state.projectIds = data.map(item => item.id)
        store.state.projectOptions = data.map(item => {
          return {
            value: item.id,
            title: item.name
          }
        })
      }
      loading.value = false
    }
    const confirmDelete = async (record) => {
      if (record.childrenNumber * 1 !== 0) {
        proxy.$root.$message.warning('当前项目存在对应软件，无法删除')
        return
      }
      loading.value = true
      const { errCode } = await proxy.$root.$axios.deleteProjet(record.id)
      if (errCode * 1 === 0) {
        proxy.$root.$message.success('操作成功')
        searchProjetList()
      }
      loading.value = false
    }
    const handleProject = async (formState, imgFileData) => {
      loading.value = true
      let errCode = ''
      if (modalConfig.type === 1) {
        const data = await proxy.$root.$axios.addProjet({ ...formState, imgFileData })
        errCode = data.errCode
      } else if (modalConfig.type === 3) {
        if (imgFileData === '') {
          const data = await proxy.$root.$axios.modifyProject(formState.id, { ...formState })
          errCode = data.errCode
        } else {
          const data = await proxy.$root.$axios.modifyProject(formState.id, { ...formState, imgFileData })
          errCode = data.errCode
        }
      }
      if (errCode * 1 === 0) {
        proxy.$root.$message.success('操作成功')
        searchProjetList()
        modalConfig.visible = false
      }
      loading.value = false
    }
    const showModal = (title, type, record) => {
      modalConfig.title = '项目' + title
      modalConfig.type = type
      modalConfig.projectRow = record
      modalConfig.visible = true
    }
    const RefProjectSetting = ref(null)
    const handleOk = () => {
      RefProjectSetting.value.onSubmit()
    }
    const handlePreview = (imgSrc) => {
      imgModal.src = imgSrc
      imgModal.visible = true
    }
    const handleCancel = () => {
      imgModal.visible = false
    }
    const customRow = (record, index) => {
      return {
        onMouseenter: (event) => {
          // 兼容IE
          var ev = event || window.event
          ev.target.draggable = true
        },
        onDragstart: (event) => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到源目标数据
          dragStartRow.value = { ...record }
        },
        onDragover: (event) => {
          // 兼容 IE
          var ev = event || window.event
          // 阻止默认行
          ev.preventDefault()
        },
        onDrop: (event) => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到目标数据
          dropRow.value = { ...record }
          const dragStartRowIndex = dragStartRow.value.serialNumber - 1
          const dragStartRowId = dragStartRow.value.id
          const dropRowIndex = record.serialNumber - 1
          const dropRowId = record.id
          dataSource.value[dragStartRowIndex] = { ...record }
          dataSource.value[dropRowIndex] = dragStartRow.value
          dataSource.value = dataSource.value.map((item, index) => {
            return {
              ...item,
              serialNumber: index + 1
            }
          })
          proxy.$root.$axios.getProjetList({
            [dragStartRowId]: dropRowIndex,
            [dropRowId]: dragStartRowIndex
          })
        }
      }
    }
    return {
      logined: computed(() => store.state.logined),
      projectColumns,
      loading,
      dataSource,
      modalConfig,
      imgModal,
      confirmDelete,
      handleProject,
      showModal,
      RefProjectSetting,
      handleOk,
      handleSoftTo (id) {
        context.emit('handle-project-soft', id)
      },
      handlePreview,
      handleCancel,
      pagination,
      customRow
    }
  }
}
</script>

<style lang='less' scoped>
  .imgUrl {
    cursor: pointer;
  }
</style>
